package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.enums.IsHotEnum;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-16
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {
    @Resource
    private IServeItemService serveService;
    @Resource
    private IRegionService regionService;
    /**
     * 根据区域id，分页查询该区域下的服务列表
     * @param dto
     * @return
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO dto) {
        return PageHelperUtils.selectPage(dto, ()-> baseMapper.queryServeByRegionId(dto.getRegionId()));
    }
    @Transactional
    @Override
    public void addBatch(List<ServeUpsertReqDTO> dtoList) {
        if (CollUtil.isEmpty(dtoList)){
            throw new ForbiddenOperationException("添加的服务项不能为空");
        }
        //1.循环便利dtoList集合，添加区域集合
        for (ServeUpsertReqDTO dto : dtoList) {
            //判断服务项是否存在,且装填是否为启用
            ServeItem byId = serveService.getById(dto.getServeItemId());
            if (byId == null || byId.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
                throw new ForbiddenOperationException("服务项不存在或未启用");
            }
            //判断同一个区域下的服务项是否重复添加
            Serve serve = this.lambdaQuery()
                    .eq(Serve::getRegionId, dto.getRegionId())
                    .eq(Serve::getServeItemId, dto.getServeItemId())
                    .one();
            if (serve != null){
                throw new ForbiddenOperationException("该区域下已存在该服务项");
            }
            //添加服务项
            Serve serve1 = BeanUtil.copyProperties(dto, Serve.class);
            Region region = regionService.getById(dto.getRegionId());
            serve1.setCityCode(region.getCityCode());
            boolean save = this.save(serve1);
            if (!save){
                throw new ForbiddenOperationException("添加服务项失败");
            }
        }

    }

    /**
     * 上架服务
     * @param id 服务id
     */
    @Override
    public void onSale(Long id) {
        Serve serve = this.getById(id);
        if (ObjectUtil.isNull(serve) || !(serve.getSaleStatus()==FoundationStatusEnum.INIT.getStatus()
                || serve.getSaleStatus()==FoundationStatusEnum.DISABLE.getStatus())
        ){
            throw new ForbiddenOperationException("服务项不存在或已上架");
        }
        ServeItem serveItem = serveService.getById(serve.getServeItemId());
        if (serveItem == null || serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("服务项不存在或未启用");
        }
        boolean update = this.lambdaUpdate().set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .eq(Serve::getId, id)
                .update();
        if (!update){
            throw new ForbiddenOperationException("上架失败");
        }
    }

    /**
     * 删除服务
     * @param id 服务id
     */
    @Override
    public void delete(Long id) {
        // 检查服务的状态是否为草稿
        Serve serve = this.getById(id);
        Integer saleStatus = serve.getSaleStatus();
        if (ObjectUtil.isNull(serve)  ||  saleStatus!=FoundationStatusEnum.INIT.getStatus()  ){
            throw new ForbiddenOperationException("只有草稿状态的服务才能被删除");
        }
        //删除
       baseMapper.deleteById(id);

    }

    /**
     * 下架服务
     * @param id
     */
    @Override
    public void offSale(Long id) {
        Serve serve = this.getById(id);
        // 检查服务是否存在并且处于上架状态
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务项不存在或已下架");
        }
        ServeItem serveItem = serveService.getById(serve.getServeItemId());
        if (serveItem == null || serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("服务项不存在或未启用");
        }
        //判断服务是否为热门服务，如果是则不能下架
        if (serve.getIsHot() == IsHotEnum.HOT.getStatus()) {
            throw new ForbiddenOperationException("热门服务不能下架");
        }


        // 将服务状态设置为下架状态
        boolean update = this.lambdaUpdate()
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .eq(Serve::getId, id)
                .update();

        if (!update) {
            throw new ForbiddenOperationException("下架失败");
        }


    }

    /**
     * 设置服务为热门服务
     * @param id
     */
    @Override
    public void onHot(Long id) {
        Serve serve = this.getById(id);
        // 检查服务是否存在并且处于上架状态
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务项不存在或已下架");
        }

        ServeItem serveItem = serveService.getById(serve.getServeItemId());
        if (serveItem == null || serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("服务项不存在或未启用");
        }
        // 检查服务是否已经是热门服务
        if (serve.getIsHot().equals(IsHotEnum.HOT.getStatus())) {
            throw new ForbiddenOperationException("服务已经是热门服务");
        }
        boolean update = this.lambdaUpdate()
                .set(Serve::getIsHot, IsHotEnum.HOT.getStatus()  )
                .eq(Serve::getId, id)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("设置热门服务失败");
        }
    }

    /**
     * 取消热门服务
     * @param id
     */
    @Override
    public void offHot(Long id) {
         Serve serve = this.getById(id);
         if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
             throw new ForbiddenOperationException("服务项不存在或已下架");
         }
         boolean update = this.lambdaUpdate()
                 .set(Serve::getIsHot, IsHotEnum.NOT_HOT.getStatus()  )
                 .eq(Serve::getId, id)
                 .update();
         if (!update) {
             throw new ForbiddenOperationException("取消热门服务失败");
         }
    }

    /**
     * 根据区域id和销售状态查询服务数量
     * @param id
     * @param status
     * @return
     */
    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long id, int status) {

        return  baseMapper.queryServeCountByRegionIdAndSaleStatus(id,status);
    }

    @Override
    public Serve updatePrice(Long id, BigDecimal price) {
        //1.更新服务价格
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if(!update){
            throw new ForbiddenOperationException("修改服务价格失败");
        }
        return baseMapper.selectById(id);
    }


}
